//
//  FortunePaperViewController.m
//  SmileWeather
//
//  Created by lanou3g on 15/9/22.
//  Copyright (c) 2015年 陶天海. All rights reserved.
//

#import "FortunePaperViewController.h"
#import "FortunePaperCollectionViewCell.h"
#import "FortunePaperModel.h"
#import "PaperDetailViewController.h"
@interface FortunePaperViewController ()
@property (nonatomic, strong)NSMutableArray *paperArr;
@property (nonatomic, strong)UICollectionView *collectionView;

@property (nonatomic, strong)UIAlertView *alert;
@property (nonatomic, strong)UIActivityIndicatorView *act;

@property (nonatomic, assign)NSInteger LimNum;
@property (nonatomic, assign)NSInteger startNum;

@property (nonatomic, strong)UILabel *label;
@end

@implementation FortunePaperViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.navigationController.navigationItem.title = @"可爱壁纸";
    //创建布局对象
    UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc] init];
    //设置布局属性
    layout.minimumLineSpacing = 20;
    //提取高度
    CGFloat width = self.view.frame.size.width;
    
    layout.itemSize = CGSizeMake((width - 20) / 3, 200);
    
    //创建集合视图
   self.collectionView = [[UICollectionView alloc] initWithFrame:self.view.bounds collectionViewLayout:layout];
    
    _collectionView.dataSource = self;
    _collectionView.delegate = self;
    _collectionView.backgroundColor = [UIColor whiteColor];
    _collectionView.showsVerticalScrollIndicator = NO;
    
    //注册
    [self.collectionView registerClass:[FortunePaperCollectionViewCell class] forCellWithReuseIdentifier:@"myCell"];
    [self.view addSubview:_collectionView];
    self.LimNum = 9;
    self.startNum = 0;
    [self reloadPaper];
    [self reloadPages];

    UIBarButtonItem *rightBtn = [[UIBarButtonItem alloc] initWithTitle:@"首页" style:(UIBarButtonItemStyleDone) target:self action:@selector(RightBackBtn)];

    self.navigationItem.rightBarButtonItem = rightBtn;
}
//返回首页按钮
- (void)RightBackBtn{
        [self transitionWithType:@"cameraIrisHollowClose" WithSubtype:kCATransitionFromTop ];
    [self.navigationController popToRootViewControllerAnimated:YES];
}
//请求数据
- (void)reloadPaper{
    [self setAlert];
   NSString *url = [NSString stringWithFormat:@"%@%ld%@%ld",kFortunePaper,self.LimNum,kFortunePaperrr,self.startNum];
    NSURL *newUrl = [NSURL URLWithString:url];
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:newUrl cachePolicy:(NSURLRequestUseProtocolCachePolicy) timeoutInterval:10.0];
    [request setHTTPMethod:@"GET"];
    [NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
    if (data == nil) {
        [_act stopAnimating];
        [_alert dismissWithClickedButtonIndex:0 animated:YES];
        [self setLabel];
    }else{
        NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:data options:(NSJSONReadingMutableContainers) error:nil];
        NSArray *object_list = dic[@"data"][@"object_list"];
        for (NSDictionary *photoDic in object_list) {
                NSDictionary *path = photoDic[@"photo"];
            FortunePaperModel *model = [[FortunePaperModel alloc] init];
            [model setValuesForKeysWithDictionary:path];
            [self.paperArr addObject:model];
            }
            [self.collectionView reloadData];
            [_act stopAnimating];
            [_alert dismissWithClickedButtonIndex:0 animated:YES];
        }
    }];
}
//懒加载
- (NSMutableArray *)paperArr{
    if (!_paperArr) {
        _paperArr = [[NSMutableArray alloc] init];
    }
    return _paperArr;
}
//加载没网状态下的label
- (void)setLabel{
    self.label = [[UILabel alloc] initWithFrame:CGRectMake(60, kHeight/2 - 50, kWidth/2 + 60, 70)];
    self.label.backgroundColor = [UIColor clearColor];
    self.label.userInteractionEnabled = YES;
    self.label.textColor = [UIColor blackColor];
    self.label.text = @"网络不好,请重试";
    self.label.textAlignment = NSTextAlignmentCenter;
    [self.view addSubview:self.label];
    TapImageView *imageView = [[TapImageView alloc] initWithFrame:CGRectMake(185, 20, 30, 30) target:self action:@selector(tapImage)];
    imageView.image = [UIImage imageNamed:@"dateUp"];
    [self.label addSubview:imageView];
}
//手势
- (void)tapImage{
    [self.label removeFromSuperview];
    [self reloadPaper];
}
- (void)setAlert{
    self.alert = [[UIAlertView alloc] initWithTitle:@"正在加载..." message:nil delegate:nil cancelButtonTitle:nil otherButtonTitles:nil, nil];
    self.act = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:(UIActivityIndicatorViewStyleGray)];
    [_act setFrame:CGRectMake(120, 48, 37, 37)];
    [_alert addSubview:_act];
    [_act startAnimating];
    [_alert show];
}
//下拉刷新
- (void)reloadPages{
    __block FortunePaperViewController *start = self;
    [self.collectionView addFooterWithCallback:^{
        start.LimNum += 9;
        start.startNum += 9;
        start.paperArr = nil;
        //重新解析数据
        [start reloadPaper];
        //刷新(解析数据有刷新)
       //[start.collectionView reloadData];
        //停止刷新
        [start.collectionView footerEndRefreshing];

    }];
}
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{
    return self.paperArr.count;
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
    
    FortunePaperCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"myCell" forIndexPath:indexPath];
    //获取模型
    if (self.paperArr.count > 0) {
    FortunePaperModel *paperModel = self.paperArr[indexPath.row];
    [cell.headerView sd_setImageWithURL:[NSURL URLWithString:paperModel.path]placeholderImage:[UIImage imageNamed:@"ipad_bg"]];
    }
    return cell;
}
- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath{
    PaperDetailViewController *paperVC = [[PaperDetailViewController alloc] init];
    FortunePaperModel *paperModel = self.paperArr[indexPath.row];
    paperVC.model = paperModel;
    paperVC.number = indexPath.row;
    paperVC.ScollreArr = self.paperArr;
    [self transitionWithType:@"rippleEffect" WithSubtype:kCATransitionFromRight ];
    [self.navigationController pushViewController:paperVC animated:YES];
}
#pragma CATransition动画实现
- (void)transitionWithType:(NSString *) type WithSubtype:(NSString *) subtype{
    //创建CATransition对象
    CATransition *animation = [CATransition animation];
    //设置运动时间
    animation.duration = 0.7f;
    //设置运动type
    animation.type = type;
    if (subtype != nil) {
    //设置子类
    animation.subtype = subtype;
    }
    //设置运动速度
    animation.timingFunction = UIViewAnimationOptionCurveEaseInOut;
    [self.navigationController.view.layer addAnimation:animation forKey:@"animation"];
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
}

@end
